package com.rfzn.mynfc

import android.app.PendingIntent
import android.content.Intent
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.os.Bundle
import android.os.Parcelable
import android.util.Log
import androidx.appcompat.app.AppCompatActivity

/**
 * Created by james on 9/10/15.
 */
abstract class NFCActivity : AppCompatActivity() {

    private lateinit var nfcAdapter: NfcAdapter
    private lateinit var mPendingIntent: PendingIntent

    companion object {
        private const val TAG = "MyNFCActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG, "onCreate ")

        initNFC()
    }

    private fun initNFC() {
        nfcAdapter = NfcAdapter.getDefaultAdapter(this)
        mPendingIntent = PendingIntent.getActivity(this, 0, Intent(this, javaClass), PendingIntent.FLAG_UPDATE_CURRENT)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        resolveIntent(intent)
    }

    private fun resolveIntent(intent: Intent) {
            val tag = intent.getParcelableExtra<Parcelable>(NfcAdapter.EXTRA_TAG) as Tag
            val tagId = HexUtils.flipHexStr(HexUtils.bytesToHexString(tag.id))
            val icCardId=HexUtils.hexStringToDecimal(tagId)
            Log.i(TAG, "idCardId=$icCardId")
            onNfcTouch(icCardId)
    }



    /**
     * 当接受到可处理的NCF时回调该方法
     */
    protected abstract fun onNfcTouch(icCardId:String)


    public override fun onResume() {
        super.onResume()
        //设置当前activity为栈顶
        nfcAdapter.enableForegroundDispatch(
            this,
            mPendingIntent,
            null,null
        )
    }

    override fun onPause() {
        super.onPause()
        //恢复栈
        nfcAdapter.disableForegroundDispatch(this)
    }


}